package com.ruoyi.api;

import com.ruoyi.common.annotation.Anonymous;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.*;
import java.security.cert.X509Certificate;
import java.util.*;
import java.util.Date;

@RestController
@RequestMapping("/api/tshock")
@CrossOrigin("*")
@Anonymous
public class TshockInfoController {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    // 处理HTTPS证书问题（测试用）
    private RestTemplate createRestTemplate() {
        try {
            TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        public X509Certificate[] getAcceptedIssuers() { return null; }
                        public void checkClientTrusted(X509Certificate[] certs, String authType) {}
                        public void checkServerTrusted(X509Certificate[] certs, String authType) {}
                    }
            };

            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
            HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true);

            return new RestTemplate();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 验证REST接口连通性（GET方式，通过查询参数传递数据）
     */
    @GetMapping("/check-connectivity") // 改为GET请求
    public Map<String, Object> checkConnectivity(
            @RequestParam String serverIp,    // 从查询参数获取IP
            @RequestParam String restPort,    // 从查询参数获取端口
            @RequestParam String token        // 从查询参数获取Token
    ) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 参数验证
            if (serverIp.isEmpty() || restPort.isEmpty() || token.isEmpty()) {
                result.put("success", false);
                result.put("message", "参数不完整，请检查IP、端口和Token");
                return result;
            }

            // 构建目标URL
            String targetUrl = String.format("http://%s:%s/tokentest?token=%s",
                    serverIp, restPort, token);

            // 发送请求
            RestTemplate restTemplate = createRestTemplate();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> entity = new HttpEntity<>(headers);

            ResponseEntity<String> response = restTemplate.exchange(
                    targetUrl,
                    HttpMethod.GET,
                    entity,
                    String.class
            );

            // 处理响应
            if (response.getStatusCode().is2xxSuccessful()) {
                result.put("success", true);
                result.put("status", "200");
                result.put("response", "Token验证成功");
                result.put("detail", response.getBody());
            } else {
                result.put("success", false);
                result.put("status", response.getStatusCodeValue());
                result.put("error", "验证失败，服务器返回非成功状态");
                result.put("detail", response.getBody());
            }

        } catch (Exception e) {
            result.put("success", false);
            result.put("status", "500");
            result.put("error", "连接失败：" + e.getMessage());
            result.put("detail", e.toString());
        }

        return result;
    }

    // 其他已有方法（list/add/delete）保持不变
    public static class TshockInfo {
        // 实体类代码保持不变
        private Long id;
        private String serverName;
        private String creatorName;
        private String serverIp;
        private Integer serverPort;
        private Integer restPort;
        private String uuid;
        private String token;
        private Date createTime;

        // getter和setter方法...
        public Long getId() { return id; }
        public void setId(Long id) { this.id = id; }
        public String getServerName() { return serverName; }
        public void setServerName(String serverName) { this.serverName = serverName; }
        public String getCreatorName() { return creatorName; }
        public void setCreatorName(String creatorName) { this.creatorName = creatorName; }
        public String getServerIp() { return serverIp; }
        public void setServerIp(String serverIp) { this.serverIp = serverIp; }
        public Integer getServerPort() { return serverPort; }
        public void setServerPort(Integer serverPort) { this.serverPort = serverPort; }
        public Integer getRestPort() { return restPort; }
        public void setRestPort(Integer restPort) { this.restPort = restPort; }
        public String getUuid() { return uuid; }
        public void setUuid(String uuid) { this.uuid = uuid; }
        public String getToken() { return token; }
        public void setToken(String token) { this.token = token; }
        public Date getCreateTime() { return createTime; }
        public void setCreateTime(Date createTime) { this.createTime = createTime; }
    }
}
